package com.tianji.promotion.utils;

import com.tianji.common.exceptions.BizIllegalException;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

@Aspect
@RequiredArgsConstructor
@Component
public class MyLockAspect implements Ordered {

    private final MyLockFactory lockFactory;

    @Around("@annotation(myLock)")
    public Object tryLock(ProceedingJoinPoint joinPoint, MyLock myLock) throws Throwable {
        //1.创建锁对象
        RLock lock = lockFactory.getLcok(myLock.lockType(), myLock.name());
        //2.尝试获取锁
        boolean isLock = myLock.strategy().tryLock(lock, myLock);
        //3.判断锁是否获取成功
        if (!isLock) {
           return null;
        }
        try {
            //3.成功获取，执行业务
            return joinPoint.proceed();
        }finally {
            //4.释放锁
            lock.unlock();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
